package com.dsteiner.xelavos.server.dao.jdo;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dsteiner.widgets.server.dao.jdo.BaseDataDaoJdo;
import com.dsteiner.widgets.server.dao.jdo.PMF;
import com.dsteiner.xelavos.client.constants.Constants;
import com.dsteiner.xelavos.client.domain.User;
import com.dsteiner.xelavos.server.dao.DataDao;
import com.dsteiner.xelavos.server.domain.File;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.images.CompositeTransform;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

public class DataDaoJdo extends BaseDataDaoJdo implements DataDao {

	public DataDaoJdo() {
		PMF.get();
	}
	
	public synchronized User getUser(String email, String password) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
        	Query query = pm.newQuery(User.class);
            query.setFilter("email == emailParam && password == passwordParam");
            query.declareParameters("String emailParam, String passwordParam ");
            query.setRange(0, 1);

            List<User> users = (List<User>) query.execute(email, password);
            if(users != null && !users.isEmpty())
            	return users.get(0);
            else
            	return null;
        } finally {
            pm.close();
        }		
	}

	public synchronized String saveFile(Blob blob, HttpServletRequest req) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			ImagesService imagesService = ImagesServiceFactory.getImagesService();
			if(blob.getBytes().length > Constants.MAX_FILE_SIZE){
				return Constants.MSG_FILE_UPLOAD_TOO_LARGE + " (actual: " + 
				Math.round((blob.getBytes().length / 1000))
				+ " Kb | maximal: "+ Math.round((Constants.MAX_FILE_SIZE / 1000))+" Kb)";
			}
	        Image oldImage = ImagesServiceFactory.makeImage(blob.getBytes());
	        
	        Transform resize = ImagesServiceFactory.makeResize(300, 300);
	        Transform feelingLucky = ImagesServiceFactory.makeImFeelingLucky();
	        CompositeTransform compositeTransform = ImagesServiceFactory.makeCompositeTransform();
	        compositeTransform.concatenate(resize);
	        compositeTransform.concatenate(feelingLucky);
	        
	        Image newImage = imagesService.applyTransform(compositeTransform, oldImage);

	        byte[] newImageData = newImage.getImageData();			
			File file = new File(new Blob(newImageData));
            pm.makePersistent(file);
			return file.getId();
		} finally {
			pm.close();
		}		
	}

}
